package com.woniuxy.project.campus.account.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.woniuxy.project.campus.account.dto.PageInfo;
import com.woniuxy.project.campus.account.dto.ResourceDto;
import com.woniuxy.project.campus.account.model.form.*;
import com.woniuxy.project.campus.account.model.Account;
import com.woniuxy.project.campus.account.param.*;
import com.woniuxy.project.campus.account.model.redisForm.LoginForm;
import com.woniuxy.project.campus.account.model.redisForm.RegisterForm;
import com.woniuxy.project.campus.account.redisClint.RedisUtil;
import com.woniuxy.project.campus.account.service.AccountService;
import com.woniuxy.project.campus.util.Result;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author 吴彦祖
 * @since 2025年02月17日
 */
@RestController
@RequestMapping("/account")
public class AccountController {

    @Resource
    private AccountService accountService;
    @Resource
    private RedisUtil redisUtil;
    /**
     * 用户注册接口
     * 此接口用于接收用户信息并进行注册操作
     * 通过POST方法访问/login路径完成用户注册
     */
    @ApiOperation(value = "用户登录", notes = "传入用户信息，进行登录操作，返回用户前端资源,签发token")
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpServletResponse response) throws Exception {
        boolean isValid1 = Validator.isMobile(loginForm.getAccount());
        if (!isValid1) {
            throw new Exception("手机号码格式错误");
        }
        LoginParam param = BeanUtil.toBean(loginForm, LoginParam.class);

        List<ResourceDto> list = accountService.login(param,response);

        return Result.success(list);
    }




    @ApiOperation("发送验证码")
    @GetMapping("/sendCode")
    public Result sendCode(@RequestParam("phone") String phone) throws Exception {
        System.out.println("手机号"+phone);
//        String api ="https://106.ihuyi.com/webservice/sms.php?method=Submit";
//        String account="C09844997";
//        String password="7e71a60be5b693f8258d7e987316f124";
//        System.out.println("手机号"+phone);
//        System.out.println("api"+api);
//        System.out.println("account"+account);
//        System.out.println("password"+password);
//        //使用hutool提供的Http工具发送请求
//        HashMap<String, Object> params = new HashMap<>();
//        params.put("account",account);
//        params.put("password",password);
//        params.put("mobile",phone);
//        params.put("format","json");
        String code=String.valueOf((int)(Math.random()*9000)+1000);
        System.out.println(code);
        String content="您的验证码是：" + code + "。请不要把验证码泄露给其他人。";
//        params.put("content",content);

//        //向第三方的接口发送请求
//        HttpResponse response = HttpRequest.post(api).form(params).execute();
//        String json = response.body();
//        String resultCode = JSONUtil.parseObj(json).get("code").toString();
//        System.out.println(resultCode);
//        if("2".equals(resultCode)){
//            System.out.println("短信验证码："+content);
//        }else{
//            throw new Exception("短信发送失败");
//        }
        redisUtil.set(RedisKey.getSendRegCodeKey(phone),code,60*5*60*1000);
//        redisUtil.incrementCdoe(RedisKey.userCodeNumKey(phone));
//        redisUtil.setExpire(RedisKey.userCodeNumKey(phone), 24 * 60 * 60);
        return Result.success(content);
    }


    @ApiOperation(value = "用户注册", notes = "传入手机验证码和用户信息，进行注册操作")
    @PostMapping("/register")
    public Result register(@ApiParam(value="注册表单",required=true) @RequestBody RegisterForm registerForm) throws Exception {

        RegisterParam param = BeanUtil.toBean(registerForm, RegisterParam.class);
        accountService.register(param);
        return Result.success(null);
    }

    /**
     * 发送短信注册接口
     * 此接口用于接收手机号码 发送验证码
     * 验证码4位随机数，有效期5分钟
     * 1分钟内 同一个手机号码只能发送一次验证码
     * 发出去的验证码存入redis，key为RedisKey.SMS_CODE_KEY+mobile
     *
     * @param mobile 手机号码
     * @return null
     * @throws Exception 手机号码格式错误 手机号码已注册,一分钟内已发送过验证码,24小时已经发送过5次验证码
     */
    @ApiOperation(value = "短信注册", notes = "手机号码，验证码，进行短信注册操作")
    @GetMapping("/smsRegistration")
    public Result smsRegistration(@ApiParam(value="手机号码",required=true) String mobile) throws Exception {
//        boolean isValid1 = Validator.isMobile(mobile);
//        if (!isValid1) {
//            throw new Exception("手机号码格式错误");
//        }
        accountService.smsRegistration(mobile);
        return Result.success(null);
    }

    //通过id获取用户信息
    @ApiOperation(value = "获取用户信息", notes = "传入用户id，获取用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo(@RequestParam("id") Integer id) throws Exception {
        String userInfo = accountService.getUserInfo(id);
        return Result.success(userInfo);
    }

    //查询商家入住申请
    @ApiOperation(value = "查询商家入住申请", notes = "传入用户id，获取用户入住申请信息")
    @GetMapping("/viewTheApplication")
    public Result viewTheApplication(@RequestHeader("token") String token) throws Exception {
        List<MerchantapplicationParam> applyInfo = accountService.viewTheApplication(token);
        return Result.success(applyInfo);
    }


    //查询超级管理员id
    @ApiOperation(value = "查询超级管理员id", notes = "传入用户id，获取用户入住申请信息")
    @GetMapping("/getSuperAdminId")
    public Result getSuperAdminId() throws Exception {
        Integer superAdminId = accountService.getSuperAdminId();
        return Result.success(superAdminId);
    }

    //根据手机号查出用户信息
    @ApiOperation(value = "根据手机号查出用户信息", notes = "传入手机号，获取用户信息")
    @GetMapping("/getUserInfoByMobile")
    public Result getUserInfoByMobile(@RequestParam("mobile") String mobile) throws Exception {
        Account userInfo = accountService.getUserInfoByMobile(mobile);
        return Result.success(userInfo);
    }

    //传入用户对象 修改用户权限
    @ApiOperation(value = "修改用户信息", notes = "传入用户对象，修改用户信息")
    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(@ApiParam(value="用户对象",required=true) @RequestBody Account account) throws Exception {
        accountService.updateUserInfo(account);
        return Result.success(null);
    }


    //查询所有维修人员
    @ApiOperation(value = "查询所有维修人员", notes = "查询所有维修人员")
    @GetMapping("/getAllRepairPerson")
    public Result getAllRepairPerson() throws Exception {
        List<Account> repairPersonList = accountService.getAllRepairPerson();
        return Result.success(repairPersonList);

    }

    //根据token 获取用户信息
    @ApiOperation(value = "根据token 获取用户信息", notes = "传入token，获取用户信息")
    @GetMapping("/getUserInfoByToken")
    public Result getUserInfoByToken(@RequestParam("id") Integer id) throws Exception {
        Account userInfo = accountService.getUserInfoByToken(id);
        return Result.success(userInfo);
    }



    //管理员查询所有用户
    @ApiOperation(value = "管理员查询所有用户", notes = "管理员查询所有用户")
    @GetMapping("/getAllUser")
    public Result getAllUser(@RequestHeader("token") String token) throws Exception {
        List<Account> userList = accountService.getAllUser(token);
        return Result.success(userList);
    }

    //把商品加入购物车

    @ApiOperation(value = "把商品加入购物车")
    @PostMapping("/addAShoppingCart")
    public Result addAShoppingCart(@RequestHeader("token") String token, @RequestBody AddAShoppingCart form) throws Exception {
        AddAShoppingCartParam bean = BeanUtil.toBean(form, AddAShoppingCartParam.class);
        bean.setToken(token);
        accountService.addAShoppingCart(bean);
        return Result.success("添购物车成功");
    }

    //删除购物车商品
    @ApiOperation(value = "删除购物车商品")
    @PostMapping("/deleteShoppingCart")
    public Result deleteShoppingCart(@RequestHeader("token") String token,@RequestBody AddAShoppingCart form) throws Exception {
        AddAShoppingCartParam bean = BeanUtil.toBean(form, AddAShoppingCartParam.class);
        bean.setToken(token);
        accountService.deleteShoppingCart(bean);
        return Result.success("删除购物车");
    }

    @ApiOperation(value = "查询购物车商品")
    @PostMapping("/MyShoppingCart")
    public Result myShoppingCart(@RequestHeader("token") String token, PageForm form) throws Exception {
       PageInfo<UserCartInfoForm>  pageInfo = accountService.MyShoppingCart(token, form);
        return Result.success(pageInfo);
    }


    //传入用户id 查询用户信息
    @ApiOperation(value = "查询用户信息", notes = "传入用户id，查询用户信息")
    @GetMapping("/getUserInfoById")
    public Result getUserInfoById(@RequestParam("id") Integer id) throws Exception {
                Account userInfo = accountService.getUserInfoById(id);
                return Result.success(userInfo);
    }


    //传入用户用户信息 新增商户
    @ApiOperation(value = "新增商户", notes = "传入用户信息，新增商户")
    @PostMapping("/addMerchant")
    public Result addMerchant(@RequestBody AccountForm accountForm) throws Exception {
        accountService.addMerchant(accountForm);
        return Result.success(null);
    }
}

